//
//  GPChatDBTool.m
//  GuaPi
//
//  Created by 23 on 2017/7/9.
//  Copyright © 2017年 Joanlove. All rights reserved.
//

#import "GPChatDBTool.h"
#import "KUserData.h"
#define kDocumentPath NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject

@interface GPChatDBTool ()

#pragma mark - 属性
/**数据库操作队列*/
@property(nonatomic,strong) FMDatabaseQueue *dbQueue;

@end


@implementation GPChatDBTool

static id _instance;

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    
    return  _instance;
}

#pragma mark - API
/**打开数据库*/
- (BOOL)openCurrentDB
{
    //判断是否登录
//    BOOL isLogin = [UserManager currentUser].isLogin;
//    if (!isLogin) {
//        NSLog(@"\n======================SQLite=======================\n");
//        NSLog(@"openCurrentUserDatabase未打开数据库:当前是未登录用户\n");
//        return NO;
//    }
    
    //2 打开数据库并初始化
    if (!self.dbQueue) {
        NSLog(@"openCurrentUserDatabase 准备打开数据库\n");
        //2.1 打开数据库(根据业务规则，确认每用户的数据库路径)
        self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:[self databaseFilePath]];
        //2.2 初始化数据库(主要是创建数据库表结构)
        [self initialDatabase];
    }
    return YES;
}


/**插入记录到指定数据表中*/
- (BOOL)gp_insertTable:(NSString *)table withSQL:(NSString *)sql
{
    if (![self openCurrentDB]) {
        return NO;
    }
    
    __block BOOL result = NO;
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
       
        result = [db executeUpdate:sql];
        
    }];
    
    return result;
}

/**查询记录*/
- (void)gp_selectTable:(NSString *)table withSQL:(NSString *)sql callback:(void(^)(FMResultSet *set))callback
{
    if (![self openCurrentDB]) {
        if (callback) {
            callback(nil);
        }
        return;
    }
    
    
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        
        FMResultSet *set = [db executeQuery:sql];
        
        if (callback) {
            callback(set);
        }
    }];
}

/**更新记录*/
- (BOOL)gp_updateTable:(NSString *)table withSQL:(NSString *)sql
{
    if (![self openCurrentDB]) {
        return NO;
    }
    
    __block BOOL result = NO;
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        
        result = [db executeUpdate:sql];
        
    }];
    
    return result;
}




#pragma mark - 私有工具方法
/**返回数据库的路径*/
- (NSString *)databaseFilePath
{
    //1 获取用户的user_id并切换路径
    NSString *user_id = [KPartyView unarchive].uid;
    user_id = user_id.length? user_id: @"00000000000000";
    
    //2 构造数据库名称
    NSString *dbName = [NSString stringWithFormat:@"%@_%@.sqlite",kProfileDBPrefix, user_id];
    
    //3 拼接数据库路径
    NSString *dbPath = [kDocumentPath stringByAppendingPathComponent:dbName];
    NSLog(@"数据库路径:%@\n",dbPath);
    
    //4 返回
    return dbPath;
}

/**初始化数据库*/
- (void)initialDatabase
{
    ///初始化聊天消息表
    [self createTableWithSQL:SQL_CREATE_Profile tablName:DB_CHAT_TABLE_PROFILE];
}

/**根据SQL语句创建数据表*/
- (BOOL)createTableWithSQL:(NSString *)sql tablName:(NSString *)tableName
{
    //1 判断表名是否为空或者空格
    if (tableName == nil || tableName.length == 0 || [tableName rangeOfString:@" "].location != NSNotFound) {
        NSLog(@"Error, table name: %@ format error.",tableName);
        return NO;
    }
    
    //2 拼接最终SQL语句
    sql = [NSString stringWithFormat:sql,tableName];
    
    //3 执行SQL语句
    __block BOOL result;
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        
        result = [db executeUpdate:sql];
        
    }];
    if (!result) {
        NSLog(@"\n创建表(%@)失败 SQL语句是:%@\n",tableName,sql);
    }
    
    // 返回结果
    return result;
}



@end
















